package server

import (
	"io/ioutil"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"inspur.com/cloudware/controller"
	"inspur.com/cloudware/controller/host"
	"inspur.com/cloudware/controller/user"
	_ "inspur.com/cloudware/docs"
	"inspur.com/cloudware/middleware"
)

// NewRouter 路由配置
func NewRouter() *gin.Engine {
	r := gin.Default()

	// 中间件, 顺序不能改
	r.Use(middleware.Session(os.Getenv("SESSION_SECRET")))
	r.Use(middleware.Cors())
	// r.Use(middleware.CurrentUser())
	// 开启swag路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	//到UI的路由
	r.GET("/", func(c *gin.Context) {
		content, err := ioutil.ReadFile("./ui/index.html")
		if err != nil {
			c.Writer.WriteHeader(404)
			c.Writer.WriteString("Not Found")
			return
		}
		c.Writer.WriteHeader(200)
		c.Writer.Header().Add("Accept", "text/html")
		c.Writer.Write(content)
		c.Writer.Flush()
	})
	r.StaticFS("/css", http.Dir("./ui/css"))
	r.StaticFS("/fonts", http.Dir("./ui/fonts"))
	r.StaticFS("/img", http.Dir("./ui/img"))
	r.StaticFS("/js", http.Dir("./ui/js"))
	r.StaticFile("/favicon.ico", "./ui/favicon.ico")
	// 路由
	v1 := r.Group("/api/v1")
	{
		v1.POST("ping", controller.Ping)

		// 使用 ?name=Sheldon传参数
		v1.GET("testlog", controller.TestLog)

		// 使用 body  json格式传参数
		v1.GET("testpost", controller.TestPost)

		// 使用 body  json格式传参数
		v1.GET("testpoststruct", controller.TestPost)

		// 用户登录
		v1.POST("user/register", user.UserRegister)

		// 用户登录
		v1.POST("user/login", user.UserLogin)

		// AddHost
		v1.POST("host", host.AddHost)

		// GetHostByID
		v1.GET("host", host.GetHostByID)

		// GetHostList
		v1.GET("hosts", host.GetHostList)

		// 需要登录保护的
		auth := v1.Group("")
		auth.Use(middleware.JWTAuthRequired())
		{
			// User Routing
			auth.GET("user/me", user.UserMe)
			auth.DELETE("user/logout", user.UserLogout)
		}
	}
	// ws相关路由
	ws_v1 := r.Group("/ws/v1")
	{
		// GetHostByID
		ws_v1.GET("connect", controller.WsConnect)
		ws_v1.POST("/:hostid/sendmessage", controller.SendMsgToAgent)
		ws_v1.GET("agents", controller.GetOnlineAgents)
	}
	return r
}
